<?php
namespace Mobile\Controller;
use Mobile\Model\memberModel;
use Mobile\Model\keywordModel;

class WeixinController extends WechatController
{
    public $access_token;
    public $keywordModel;
    public $memberModel;
    public $type;
    public $openid;

    
    public function __construct() {
        parent::__construct();
        $this->memberModel = new memberModel();
        $this->keywordModel = new keywordModel();
        //file_put_contents("weixin.txt", file_get_contents("php://input"));
        //$this->valid();//明文或兼容模式可以在接口验证通过后注释此句，但加密模式一定不能注释，否则会验证失败
        $this->openid = $this->getRev()->getRevFrom();//openid
        $this->type = $this->getRev()->getRevType();//消息类型

    }
    
    /*
     * 更新用户资料
     */
    protected function _updateUserInfo($data){
         
        $unionid = set_default($data,'unionid');//联合id
        $openid = set_default($data,'openid');//联合id
        $res = false;
        if($data){
            if($unionid){
                //从数据库取用户信息
                $where = array('unionid' => $unionid);
                $res = $this->_updateU($where,$data);
    
            }else{
                //没有联合id
                $where = array('openid' => $openid);
                $res = $this->_updateU($where,$data);
            }
        }
        return $res;
    }

    /*
     * 更新用户
     */
    protected function _updateU($where,$user_data){
        $uinfo = $this->memberModel->getMember($where);
        if($uinfo){
            //如果找到了,更新用户信息
            
            $user_data['last_login_ip'] = get_client_ip();
            $user_data['last_login_time'] = date("Y-m-d H:i:s");
            $user_data['login_times'] = array('exp','login_times+1');
            
            $res = $this->memberModel->editMember($where,$user_data);//更新
        }else{
            //没找到,添加
            $user_data['status'] = 1;
            $user_data['last_login_ip'] = get_client_ip();
            $user_data['last_login_time'] = date("Y-m-d H:i:s");
            $user_data['login_times'] = 1;
            $user_data['create_time'] = date("Y-m-d H:i:s");
            $user_data['update_time'] = date("Y-m-d H:i:s");
            $user_data['role_id'] = 2;
            $user_data['is_change_username'] = 0;
            $user_data['regfrom'] = "subscribe";
            
            $res = $this->memberModel->addMember($user_data);
        }
        return $res;
    }
    
    //获取微信用户信息
    protected function _get_member_wxinfo($wxuser){
        $subscribe = set_default($wxuser,"subscribe");
        $openid = set_default($wxuser,"openid");
        
        //如果没有关注,只跟新基本信息
        if(!$subscribe){
            $user_data = array(
                "openid" => $openid,
                "unionid" => set_default($wxuser,"unionid"),
                "subscribe" => set_default($wxuser,"subscribe"),
            );
        }else{
            //如果已经关注,更新全部信息
            $user_data = array(
                "openid" => $openid,
                "nickname" => set_default($wxuser,"nickname"),
                "sex" => set_default($wxuser,"sex"),
                "province" => set_default($wxuser,"province"),
                "city" => set_default($wxuser,"city"),
                "country" => set_default($wxuser,"country"),
                "headimgurl" => set_default($wxuser,"headimgurl"),
                "privilege" => set_default($wxuser,"privilege"),
                "unionid" => set_default($wxuser,"unionid"),
                "groupid" => set_default($wxuser,"groupid"),
                "subscribe" => set_default($wxuser,"subscribe"),
                "language" => set_default($wxuser,"language"),
                "subscribe_time" => set_default($wxuser,"subscribe_time"),
                "remark" => set_default($wxuser,"remark"),
            );
        }
        return $user_data;
    }
    
    /*
     * 文本消息处理
     */
    protected function _receiveText($content){
    
        //用if语句进行路由分发
        if($content == "110"){
            $res = $this->text("报警请拨110");
            return $res;
        }else if($content == "119"){
            $res = $this->text("火警请拨119");
            return $res;
        }else if(is_numeric($content)){
            $res = $this->text("你发了一个数字");
            return $res;
        }else if(in_array($content,array("王思聪","马云","王健林","刘强东","章泽天"))){
            $res = $this->text("你发了一个人");
            return $res;
        }
        #xiaojun:多客服处理
        else if(in_array($content,array("售前客服", "售前", "客服", "在线客服"))){
           // return $this->serviceConnection(1);
            $res = $this->text("请联系人人转技术王海涛 18683317698");
        }else if(in_array($content,array("售后客服", "售后"))){
            $res = $this->text("请联系人人转技术王海涛 18683317698");
           // return $this->serviceConnection(2);
        }
    
        else{
            //按普通关键词处理
            $res = $this->_do_keyword($content);
            return $res;
        }
    
    }
    
    
    /*
     * 从数据库取关键词列表
     */
    protected function _get_keyword_list(){
        //从数据库中取出所以的关键词
        $where = array(
            "r_status" => 1,
        );
        $res = $this->keywordModel->order("id DESC")->where($where)->select();
        return $res;
    }
    
    
    /*
     * 关键词回复消息
     */
    protected function _replymsg_ready($data = null){
        if($data){
            //回复消息 $data 单条记录
            $r_type = set_default($data,'r_type');
            $reply_text = set_default($data,'reply_text');
            
            if($r_type == 1){
                //文本消息
                $res = $this->text($reply_text);
                return $res;
            }else{
                //其他类型消息
                $res = $this->text("暂时只支持图文和文本消息!");
                return $res;
            }
        }else{
            $res = $this->text("管理员请设置系统默认回复!");
            return $res;
        }
    }
    
    /*
     * 普通关键词处理
     */
    protected function _do_keyword($content){
        $klist = $this->_get_keyword_list();
      
        if($klist){
            //关键词表不为空
            foreach($klist as $k=>$v){
                $new_key[$v['id']] = $v['keyword'];
                $new_data[$v['id']] = $v;
            }
    
            //判断发送的句子是否在关键词表里(精准匹配)
            if(in_array($content, $new_key)){
                //找到了关键词
                $reply_id = array_search($content, $new_key);//取得对应的id
                $data = $new_data[$reply_id];
                //回复消息
                $res = $this->_replymsg_ready($data);
                return $res;
            }
    
            //精准匹配没匹配到,再进行模糊匹配
            //判断关键词列表是否有包含于发送的句子中的, 模糊匹配
            foreach($new_data as $k=>$v){
                // is_jingzhun 是否精准匹配,1精准匹配,0模糊匹配(默认)
                if(($v['is_jingzhun'] == 0) && (stripos($content,$v['keyword']) !== false)){
                    //匹配到了
                    $reply_id = $v['id'];
                    //回复消息
                    $res = $this->_replymsg_ready($v);
                    return $res;
                }
            }
    
            //没有匹配到,使用默认关键字defaults
            $data = $this->keywordModel->getKeyword(array("keyword"=>'defaults'));
            $res = $this->_replymsg_ready($data);
            return $res;
        }
    
        //关键词表为空
        $res = $this->_replymsg_ready();
        return $res;
    
    }
    
    /*
     * 图片消息处理
     */
    protected function _receiveImage(){
        $res = $this->text("你发的照片收到了~");
        return $res;
    }
    
    /*
     * 事件消息处理
     */
    protected function _receiveEvent(){
        $type = $this->getRev()->getRevEvent();
        $event = set_default($type,'event');
        $key = set_default($type,'key');
    
        #xiaojun:多客服会话状态状态修改
        switch ($event) {
            case "kf_create_session":#创建会话
                #$sessionData['touser'] = trim($this->getRev()->getRevFrom());
                #$sessionData['msgtype'] = "text";
                #$sessionData['text'] = array('content' => "会话已创建，请发送信息与客服沟通！");
                #TODO
                break;
            case "kf_close_session":#关闭会话
                $sessionData['touser'] = trim($this->getRev()->getRevFrom());
                $sessionData['msgtype'] = "text";
                $sessionData['text'] = array('content' => "当前客服已关闭会话！如果您的问题还未得到解决请重新发送“售前客服/售后客服”接入会话！");
                #TODO
                break;
            case "kf_switch_session":#转移会话
                #TODO 转移会话暂时未做处理
                break;
            default:
                ;
                break;
        }
        if ($sessionData) {
            #会话状态改变时，给用户发送通知
            $res = $this->sendCustomMessage($sessionData);
        }
    
    
        //扫描带参数二维码事件处理
        $qrcode_event = array(
            'subscribe','SCAN'
        );
        if(in_array($event,$qrcode_event)){
            //判断是否存在二维码的场景值
            $SceneId = $this->getRev()->getRevSceneId();
            if($SceneId){
                //如果存在场景id
                ///mobile/store/index/?id=40
                if(stripos($SceneId,"STORE_ID_") !== false){
                    //是店铺永久二维码
                    $res = $this->_store_qrcode_reply($SceneId);
                    return $res;
                }
    
                $res = $this->text("收到扫描带参数二维码事件:场景id为".$SceneId);
                return $res;
            }
        }
    
        //判断是否是普通关注事件
        if($event == "subscribe"){
            //是普通关注事件(不带参数)
            $res = $this->_subscribe();
            return $res;
        }
        //转交文本消息处理
        $res = $this->_receiveText($key);
        return $res;
        
        
        //$res = $this->text($key);
        //return $res;
        /*
        case 'CLICK'://点击时间
            break;
        case 'VIEW'://跳转
            break;
        case 'card_pass_check'://卡券审核通过
            break;
        case 'card_not_pass_check'://卡券审核失败
            break;
        case 'user_get_card'://用户领取卡券
            break;
        case 'user_del_card'://用户删除卡券
            break;
        case 'user_view_card'://用户浏览会员卡
            break;
        case 'user_consume_card'://用户核销卡券
        */

    
    

    }
    
    /*
     * 扫描店铺二维码信息回复
     * TODO
     */
    protected function _store_qrcode_reply($SceneId){
        /*
        $storeinfo = explode("_",$SceneId);
        $store_id = set_default($storeinfo,2);
        if($store_id){
            //找到了id
            //回复一条单图文链接消息
    
            //查找店铺信息
            $data = $this->StoreModel->where(array('id' => $store_id))->find();
            $title = set_default($data,'store_name',"欢迎光临");
            $Description = set_default($data,'description',"欢迎光临");
            $Description = mb_substr($Description,0,20,'utf-8');//截断
    
            $url = C('MOBILE_DOMAIN')."/mobile/store/index/?sid=".$store_id;
            $store_logo = set_default($data,'store_logo');
            if(!$store_logo){
                $store_logo = C('STORE_DEFAULT_WXPIC');
            }
            $newsData = array(
                "0"=>array(
                    'Title'=> $title,
                    'Description'=> $Description,
                    'PicUrl'=> $store_logo,
                    'Url'=> $url
                ));
            $res = $this->news($newsData);//准备图文信息
            return $res;
        }
        $res = $this->text("店铺推广二维码id获取失败");
        return $res;
        */
    }
    
    
    
    /*
     * 关注事件处理
     */
    protected  function _subscribe(){
        $data = $this->keywordModel->getKeyword(array("keyword"=>'subscribe'));
        $res = $this->_replymsg_ready($data);
        return $res;
    }
    
    
    /*
     * 地理位置消息处理
     */
    protected function _receiveLocation(){
        $res = $this->text("收到你的地址");
        return $res;
    }
    
    
    /*
     * 语音消息处理
     */
    protected function _receiveVoice(){
        $res = $this->text("收到你的语音");
        return $res;
    }
    
    /*
     * 视频消息处理
     */
    protected function _receiveVideo(){
        $res = $this->text("收到你的视频");
        return $res;
    }
    
    /*
     * 小视频消息处理
     */
    protected function _receiveShortvideo(){
        $res = $this->text("收到你的小视频");
        return $res;
    }
    
    
    /*
     * 链接消息处理
     */
    protected function _receiveLink(){
        $res = $this->text("收到你的小链接");
        return $res;
    }
    
    
    
    //首页
    public function rukou(){

	    //保存或更新用户信息
	    $openid = $this->getRev()->getRevFrom();
	    $userinfo = S("Userinfo".$openid);
	    //file_put_contents("weixin.txt", file_get_contents("php://input"));

	    if(!$userinfo){
	        $wxuser = $this->getUserInfo($openid);//获取用户资料
	        $wxuserinfo = $this->_get_member_wxinfo($wxuser);//处理组装用户资料
	        
	        //$userinfo['nickname'] = $this->_emoji($userinfo['nickname']);//emoji字符处理
	        //$this->text(json_encode($userinfo))->reply();
	        
	        $res = $this->_updateUserInfo($wxuserinfo);//将用户信息更新保存到数据库
	        S("Userinfo".$openid,$wxuser,3600);//缓存用户信息

	    }

		switch($this->type) {

				case "text":
				    $content= $this->getRev()->getRevContent();//获取文本
    				$res = $this->_receiveText($content);//文本消息处理
    				break;
				case "image":
				    $res = $this->_receiveImage();//图片消息处理
				    break;
				case "event":
				    $res = $this->_receiveEvent();//事件消息
				    break;
				case "location":
				    $res = $this->_receiveLocation();//地理位置消息
				    break;
				case "voice":
				    $res = $this->_receiveVoice();//语音消息
				    break;
				case "video":
				    $res = $this->_receiveVideo();//视频消息
				    break;
				case "link":
				    $res = $this->_receiveLink();//链接消息
				    break;
				case "shortvideo":
				    $res = $this->_receiveShortvideo();//链接消息
				    break;
    			default:
    				$res = $this->text("hi,Unknown message type~");//未知消息类型
		}
		
		$res->reply();//回复消息
		
	}
    
    


    
}